﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraGrid.Controls;
using DevExpress.Utils.Design;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraGrid.Columns;
using System.Collections;
using System.IO;
using DevExpress.XtraSplashScreen;

namespace DevExpress.MailClient.Win.Modules
{
    public partial class MyLockedFiles : BaseModule
    {
        frmMain CURRENT_MAIN_FORM
        { get; set; }

        #region FILE ICONS ASSOCIATIONS
        #region MEMBERS

        /// <summary>
        /// Used for containing file types and their icons information.
        /// </summary>
        private Hashtable HS_SYSTEM_ASSOCIATED_FILES_ICONS;

        private ImageSize currentSize;

        public ImageSize CurrentImageSize
        {
            get { return currentSize; }
            set { this.currentSize = value; }
        }

        public enum ImageSize
        {
            /// <summary>
            /// View image in 16x16 px.
            /// </summary>
            Small,

            /// <summary>
            /// View image in 32x32 px.
            /// </summary>
            Large
        }

        #endregion
        #endregion

        private PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY _cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY;
        [Browsable(false)]

        public PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY
        {
            get { return _cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY; }
            set
            {
                _cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY = value;

                if (_cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY != null)
                {
                    if (!_cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID.Equals(Guid.Empty))
                    {
                        ucArchiveFileViewer.CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY = _cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY;

                        PHYSICAL_FILE_FOUND = ucArchiveFileViewer.PHYSICAL_FILE_FOUND;
                    }
                }

            }
        }

        private PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE aRCHIVE_DEPARTMENT_FILE;
        [Browsable(false)]
        public PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE
        {
            get { return aRCHIVE_DEPARTMENT_FILE; }
            set
            {
                aRCHIVE_DEPARTMENT_FILE = value;
                if (!aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID.Equals(Guid.Empty))
                {
                    ucArchiveFileViewer.CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE = (from file in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILEs
                                                                                    where file.ARCHIVE_DEPARTMENT_FILE_ID.Equals(aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID)
                                                                                    select file).FirstOrDefault();
                }
            }
        }

        RibbonControl ribbon;
        FindControlManager findControlManager = null;
        FilterCriteriaManager filterCriteriaManager = null;

        bool lockUpdateCurrentMessage = true;
        public override string ModuleName { get { return Properties.Resources.MailName; } }
        public MyLockedFiles()
        {
            InitializeComponent();
            CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE = new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE();
        }

        //_sELECTED_ARCHIVE_DEPARTMENT_FILES
        public void LOAD_ARCHIVE_DEPARTMENT_FILES(List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE> _sELECTED_ARCHIVE_DEPARTMENT_FILES)
        {

            SplashScreenManager.ShowForm(typeof(DevExpress.MailClient.Win.Forms.wfMain), true, true);
            List<Data.FilesList> DS_FOLDER_FILES_LIST = new List<Data.FilesList>();

            
            for (int i = 0; i < _sELECTED_ARCHIVE_DEPARTMENT_FILES.Count; i++)
            {
                Data.FilesList sINGLE_FILE_LIST = new Data.FilesList();


                sINGLE_FILE_LIST.ARCHIVE_DEPARTMENT_FILE = _sELECTED_ARCHIVE_DEPARTMENT_FILES[i];

                List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY> aRCHIVE_DEPARTMENT_FILE_HISTORIES = (
                                        from history in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILE_HISTORies
                                        where
                                        (
                                            history.ARCHIVE_DEPARTMENT_FILE_ID.Value.Equals(_sELECTED_ARCHIVE_DEPARTMENT_FILES[i].ARCHIVE_DEPARTMENT_FILE_ID)
                                        )
                                        orderby history.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value descending
                                        select history
                                    ).ToList();
                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY aRCHIVE_DEPARTMENT_FILE_HISTORY = aRCHIVE_DEPARTMENT_FILE_HISTORIES[aRCHIVE_DEPARTMENT_FILE_HISTORIES.Count - 1];
                sINGLE_FILE_LIST.ARCHIVE_DEPARTMENT_FILE_HISTORY = aRCHIVE_DEPARTMENT_FILE_HISTORY;



                //get the extention
                string file_EXTENTION = sINGLE_FILE_LIST.ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION;

                //check if the file has it's icon associated with the windows system
                Icon fILE_ASSOCIATED_ICON = Properties.Resources.empty_file;
                Image fILE_ASSOCIATED_ICON_IMAGE = null;
                if (this.HS_SYSTEM_ASSOCIATED_FILES_ICONS.ContainsKey(file_EXTENTION))
                {
                    string fileAndParam = (this.HS_SYSTEM_ASSOCIATED_FILES_ICONS[file_EXTENTION]).ToString();

                    if (!String.IsNullOrEmpty(fileAndParam))
                    {

                        bool isLarge = false;

                        fILE_ASSOCIATED_ICON = PRO_DOCS.BLL.WIN.RegisteredFileType.ExtractIconFromFile(fileAndParam, isLarge); //RegisteredFileType.ExtractIconFromFile(fileAndParam);

                        ////The icon cannot be zero.
                        if (fILE_ASSOCIATED_ICON == null)
                        {
                            fILE_ASSOCIATED_ICON = Properties.Resources.empty_file;
                        }

                    }
                }
                fILE_ASSOCIATED_ICON_IMAGE = fILE_ASSOCIATED_ICON.ToBitmap();

                PRO_DOCS.DAL.Database.proc_ARCHIVE_DEPARTMENT_FILE_LOCKED_STATUSLoadAllUNLOCKEDByFILE_IDResult CURRENT_LOCKED_FILE =
                        PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_LOCKED_STATUSLoadAllUNLOCKEDByFILE_ID(_sELECTED_ARCHIVE_DEPARTMENT_FILES[i].ARCHIVE_DEPARTMENT_FILE_ID).FirstOrDefault();
                sINGLE_FILE_LIST.LOCKED_STATUS = (CURRENT_LOCKED_FILE != null) ? "locked" : "none";

                sINGLE_FILE_LIST.NEW_STATUS = (aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUEs.Count.Equals(0)) ? "new" : "none";

                sINGLE_FILE_LIST.ASSOCIATED_ICON_IMAGE = ConvertTo16bpp(fILE_ASSOCIATED_ICON_IMAGE);

                DS_FOLDER_FILES_LIST.Add(sINGLE_FILE_LIST);
            }

            gridControl1.DataSource = DS_FOLDER_FILES_LIST;
            if (gridView1.RowCount > 0)
            {
                FocusRow(0);

            }
            SplashScreenManager.CloseForm();
        }
        public static Bitmap ConvertTo16bpp(Image img)
        {
            var bmp = new Bitmap(img, new Size(16, 16));
            return bmp;
        }
        private void Mail_Load(object sender, EventArgs e)
        {

            this.HS_SYSTEM_ASSOCIATED_FILES_ICONS = PRO_DOCS.BLL.WIN.RegisteredFileType.GetFileTypeAndIcon();
            //CalcPreviewIndent();

            CURRENT_MAIN_FORM = (frmMain)this.ParentForm;
            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE> _aRCHIVE_DEPARTMENT_FILEs = new List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE>();

            List<PRO_DOCS.DAL.Database.GET_MY_LOCKED_FILESResult> gET_MY_LOCKED_FILESResults = new List<PRO_DOCS.DAL.Database.GET_MY_LOCKED_FILESResult>();
            gET_MY_LOCKED_FILESResults = PRO_DOCSDatabaseDataContext.GET_MY_LOCKED_FILES
                                (
                                    0,
                                    PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                                    string.Empty,
                                    DateTime.Now,
                                    DateTime.Now
                                ).ToList();

            for (int i = 0; i < gET_MY_LOCKED_FILESResults.Count; i++)
                {
                    _aRCHIVE_DEPARTMENT_FILEs.Add
                        (
                                (
                                    from files in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILEs
                                    where
                                    (
                                        files.ARCHIVE_DEPARTMENT_FILE_ID.Equals(gET_MY_LOCKED_FILESResults[i].ARCHIVE_DEPARTMENT_FILE_ID)
                                    )
                                    select files
                                ).FirstOrDefault()
                        );
                }
                LOAD_ARCHIVE_DEPARTMENT_FILES(_aRCHIVE_DEPARTMENT_FILEs);
        }

        protected override DevExpress.XtraGrid.GridControl Grid { get { return gridControl1; } }
        internal override void InitModule(DevExpress.Utils.Menu.IDXMenuManager manager, object data)
        {
            base.InitModule(manager, data);
            this.ribbon = manager as RibbonControl;
            ShowAboutRow();
        }
        void ShowAboutRow()
        {
            Timer tmr = new Timer();
            tmr.Interval = 100;
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();
        }
        void tmr_Tick(object sender, EventArgs e)
        {
            lockUpdateCurrentMessage = false;
            FocusRow(0);
            ((Timer)sender).Stop();
        }
        void FocusRow(int rowHandle)
        {
            gridView1.FocusedRowHandle = rowHandle;
            gridView1.ClearSelection();
            gridView1.SelectRow(rowHandle);
        }
        protected override void LookAndFeelStyleChanged()
        {
            base.LookAndFeelStyleChanged();
            ColorHelper.UpdateColor(ilColumns, gridControl1.LookAndFeel);
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            //if (e.Column == gcRead && e.Button == MouseButtons.Left)
            //    RaiseReadMessagesChanged(e.RowHandle);
            //if (e.Column.FieldName == "Priority" && e.Button == MouseButtons.Left)
            //    PriorityMenu.ShowPopup(gridControl1.PointToScreen(e.Location));
            //if (e.Button == MouseButtons.Right) ShowMessageMenu(gridControl1.PointToScreen(e.Location));
            //if (e.Button == MouseButtons.Left && e.Clicks == 2)
            //    EditMessage(e.RowHandle);
        }




        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //UpdateCurrentMessage();
            if (gridView1.FocusedRowHandle > -1)
            {

                Data.FilesList current_selected_file = gridView1.GetRow(e.FocusedRowHandle) as Data.FilesList;

                if (current_selected_file != null)
                {
                    CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE = (from db_file in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILEs
                                                                where db_file.ARCHIVE_DEPARTMENT_FILE_ID.Equals(current_selected_file.ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID)
                                                                select db_file).FirstOrDefault();

                    CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY = (from history in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILE_HISTORies
                                                               where history.ARCHIVE_DEPARTMENT_FILE_ID.Equals(CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID)
                                                               orderby history.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value descending
                                                               select history).FirstOrDefault();



                    CURRENT_MAIN_FORM.SET_FILES_BUTTONS_ENABABLING(CURRENT_SELECTED_ARCHIVE_DEPARTMENT_FILE, PHYSICAL_FILE_FOUND);


                }

            }
            else
            {
                CURRENT_MAIN_FORM.SET_FILES_BUTTONS_ENABABLING(new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE(), false);

            }

        }



        protected internal override void ButtonClick(string tag)
        {
            //switch (tag)
            //{
            //    case TagResources.RotateLayout:
            //        layoutControl1.Root.RotateLayout();
            //        break;
            //    case TagResources.FlipLayout:
            //        layoutControl1.Root.FlipLayout();
            //        break;
            //    case TagResources.DeleteItem:
            //        foreach (int row in gridView1.GetSelectedRows())
            //            if (row >= 0)
            //            {
            //                Data.Message message = ((Data.Message)gridView1.GetRow(row));
            //                if (message.MailType == MailTypes.Deleted)
            //                    message.Deleted = true;
            //                else
            //                    message.MailType = MailTypes.Deleted;
            //            }
            //        RaiseUpdateTreeViewMessages();
            //        break;
            //    case TagResources.NewMail:
            //        CreateNewMailMessage();
            //        break;
            //    case TagResources.Reply:
            //        CreateReplyMailMessage();
            //        break;
            //    case TagResources.ReplyAll:
            //        CreateReplyAllMailMessages();
            //        break;
            //    case TagResources.Forward:
            //        CreateForwardMailMessage();
            //        break;
            //    case TagResources.UnreadRead:
            //        foreach (int row in gridView1.GetSelectedRows())
            //            if (row >= 0)
            //                ((Data.Message)gridView1.GetRow(row)).ToggleRead();
            //        gridView1.LayoutChanged();
            //        OwnerForm.ReadMessagesChanged();
            //        break;
            //    case TagResources.CloseSearch:
            //        gridView1.Focus();
            //        break;
            //    case TagResources.ResetColumnsToDefault:
            //        OwnerForm.FilterColumnManager.SetDefault();
            //        break;
            //    case TagResources.ClearFilter:
            //        gridView1.ActiveFilter.Clear();
            //        break;
            //    case TagResources.Preview:
            //        break;
            //}
        }



        FindControl FindControl
        {
            get
            {
                foreach (Control ctrl in gridControl1.Controls)
                {
                    FindControl ret = ctrl as FindControl;
                    if (ret != null) return ret;
                }
                return null;
            }
        }
        void MakeFocusedRowVisible()
        {
            gridView1.MakeRowVisible(gridView1.FocusedRowHandle);
        }
        protected internal override void SendKeyDown(KeyEventArgs e)
        {
            base.SendKeyDown(e);
            if (e.KeyData == (Keys.E | Keys.Control))
            {
                if (FindControl != null)
                {
                    FindControl.FindEdit.Focus();
                }
            }
        }


        internal void SAVE_SELECTED_FILE_DYNAMIC_INDICIES()
        {
            PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY sAVED_ARCHIVE_DEPARTMENT_FILE_HISTORY = ucArchiveFileViewer.SAVE_SELECTED_FILE_DYNAMIC_INDICIES();
            if (sAVED_ARCHIVE_DEPARTMENT_FILE_HISTORY != null)
            {
                if (sAVED_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUEs.Count > 0)
                {
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcFileStatus, "none");
                }                
            }
        }

        private bool PHYSICAL_FILE_FOUND { get; set; }

        internal void DOWNLOAD_SELECTED_FILE()
        {
            ucArchiveFileViewer.DOWNLOAD_SELECTED_FILE();
        }

        internal void LOCK_CURRENT_FILE()
        {
            ucArchiveFileViewer.LOCK_CURRENT_FILE();
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcLockStatus, "locked");

        }

        internal void UNLOCK_CURRENT_FILE()
        {
            ucArchiveFileViewer.UNLOCK_CURRENT_FILE();
            gridView1.DeleteSelectedRows();
            //gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcLockStatus, "none");

        }
    }
}
